import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite";
import vue from "@vitejs/plugin-vue";

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

import { resolve } from "path";
const pathSrc = resolve(__dirname, "src");

import { wrapperEnv } from "./build/getEnv";
import { createProxy } from "./build/proxy";

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);

  return {
    resolve: {
      alias: {
        "@": pathSrc,
      },
    },
    server: {
      host: "0.0.0.0",
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,
      cors: true,
      // Load proxy configuration from .env.development
      proxy: createProxy(viteEnv.VITE_PROXY),
    },
    plugins: [
      vue(),
      AutoImport({
        // targets to transform
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
        // global imports to register
        imports: [
          // 插件预设支持导入的api
          "vue",
          "vue-router",
          "pinia",
          // 自定义导入的api
          "@vueuse/core"
        ],
        eslintrc: {
          enabled: false, // Default `false`
          filepath: "./.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
        resolvers: [
          // 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
          ElementPlusResolver(),
        ],
        // 配置文件生成位置(false:关闭自动生成)
        dts: "./auto-imports.d.ts",
      }),
      Components({
        // 指定组件所在文件夹的位置，默认是src/components
        // dirs: ["src/**/components"],
        resolvers: [
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
        ],
        extensions: ["vue"], //文件扩展
        // 配置type文件生成位置
        dts: "src/types/components.d.ts",
      }),
    ],
  };
});
